package com.ba.security.session;

import java.io.Serializable;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.ValidatingSession;
import org.apache.shiro.session.mgt.eis.CachingSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import com.ba.redis.RedisClusterCacheStorageImpl;
import com.ba.utils.SerializeUtil;

//对session进行CRUD，这里利用redis，便于后续集群处理。
public class CustomSessionDAOImpl extends CachingSessionDAO{

    @Autowired
    private RedisClusterCacheStorageImpl redisCacheStorage;
    
    
    @Override
    protected void doUpdate(Session session) {
        if(session instanceof ValidatingSession && !((ValidatingSession)session).isValid()) {
            return; //如果会话过期/停止没必要再更新了
        }
        //TODO此处更新session
        redisCacheStorage.update(session.getId(),session);
    }

    @Override
    protected void doDelete(Session session) {
        Serializable sessionId = session.getId();
        redisCacheStorage.delete(sessionId);
    }

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId =generateSessionId(session);
        assignSessionId(session, sessionId);
        //注意，这里是拿不到sessionId or  session，报错，导致jedis set 失败 等原因。  疑问：这里不需要调用关闭redis方法？？
        redisCacheStorage.set(SerializeUtil.serialize(sessionId), session);
        return sessionId; 
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        Session session = null;
        if(sessionId == null){
            return null;
        }
        session = (Session)redisCacheStorage.get(SerializeUtil.serialize(sessionId));
        return session;
    }
}
